package com.solution.wx.home.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solution.admin.home.constants.IndexConstants;
import com.solution.admin.home.entity.ModuleAndConfigEntity;
import com.solution.admin.home.entity.SiteConfigItemEntity;
import com.solution.admin.home.entity.SiteModuleEntity;
import com.solution.admin.home.service.IndexService;
import com.solution.admin.home.service.SiteModuleService;
import com.solution.admin.message.constants.MessageConstants;
import com.solution.admin.message.constants.MessageConstants.MessageType;
import com.solution.admin.message.entity.MessageEntity;
import com.solution.admin.message.service.MessageService;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.service.OrderService;
import com.solution.admin.product.entity.ProductCategoryEntity;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.service.ProductCategoryService;
import com.solution.admin.product.service.ProductService;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.controller.BaseController;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.order.entity.CustomerOrderStatisticsEntity;
import com.solution.wx.common.constants.PublicConstants;

/**
 * 微信首页控制层
 * 首页分为几个模块：
 * 
 * 0、关键字搜索
 * 1、加载顶部广告图片
 * 2、加载首页8大模块
 * 3、加载商户通知公告
 * 4、加载楼层  
 * 5、为你推荐商品列表
 * （以上数据均从redis 缓存中加载）
 * @author llp
 * @date 2017-09-26 14:44:49
 */
@RequestMapping("/wx")
@Controller("wxIndexController")
public class IndexController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(IndexController.class);

	@Autowired
	private SiteModuleService siteModuleService;
	
	@Autowired
	private IndexService indexService;
	
	@Autowired
	private ProductCategoryService productCategoryService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private KeyMapService keyMapService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private MessageService messageService;
	
	/**
	 * 跳转网站首页
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author llp
 	 * @date 2017-09-26 14:44:49
	 */
	@RequestMapping("/index")
	public String toListSiteModulePage(HttpServletRequest request) {
		request.setAttribute(PublicConstants.CURRENT_PAGE_KEY, PublicConstants.PAGE_HOME);
		
		Map<String, Object> param = new HashMap<String, Object>();
		// 网站运营的所有模块
		param.put("key", IndexConstants.REDIS_KEY_EB_SITE_MODULE_LIST);
		Map<String, SiteModuleEntity> smMap = indexService.listSiteModule(param);
		
		// 查询微信首页楼层
		List<ModuleAndConfigEntity>  wxFloorList = new ArrayList<ModuleAndConfigEntity>(); 
		Map<String, List<SiteConfigItemEntity>>  scMap = null;
		try {
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_WX_FLOOR);
			// 从redis 中查询楼层配置信息
			scMap = indexService.listIndexProductFloor(param);
			
			if(scMap != null && scMap.size() > 0){
				for(Map.Entry<String, List<SiteConfigItemEntity>>  entry : scMap.entrySet()){
					ModuleAndConfigEntity  fie = new ModuleAndConfigEntity(smMap.get(entry.getKey()),entry.getValue());
					wxFloorList.add(fie);
				}
			}
			request.setAttribute("floorList", wxFloorList);
			
		} catch (Exception e) {
			handleException("查询微信首页楼层信息", logger, e);
		}
		
		// 获取消息、资讯
		try {
			MessageEntity messageSys = null;
			MessageEntity messageDyn = null;
			
			// 用户未登录时，查询最新一条系统消息进行展示
			if (!isLogin(request)) {
				// 查询最近一条系统消息
				MessageEntity lastMessage = messageService.getLastMessage(MessageConstants.MessageType.TYPE_SYSTEM.toString());
				messageSys = lastMessage; 
			}else{
				Long userId = getUserId();
				// 系统消息
				List<MessageEntity> messageSystemList = messageService.getWxMessageList(MessageType.TYPE_SYSTEM, userId, 1);
				if(null != messageSystemList && messageSystemList.size() > 0) {
					messageSys = messageSystemList.get(0);
				}
				// 业界动态消息
				List<MessageEntity> messageDynamicList = messageService.getWxMessageList(MessageType.TYPE_DYNAMIC, userId, 1);
				if(null != messageDynamicList && messageDynamicList.size() > 0) {
					messageDyn = messageDynamicList.get(0);
				}
			}
			
			//首先加入
			if(null != messageSys) {
				request.setAttribute("message", messageSys);
			}
			if(null != messageSys && null != messageDyn) {
				//添加时间较新的
				if(messageSys.getModifyTime().after(messageDyn.getModifyTime())) {
					request.setAttribute("message", messageSys);
				} else {
					request.setAttribute("message", messageDyn);
				}
			}
        } catch (Exception e) {
        	List<MessageEntity> messageList = messageService.listMessage(null);
        	if(null != messageList && messageList.size() > 0) {
				request.setAttribute("message", messageList.get(0));
			}
        	e.printStackTrace();
        }
		
		// 查询微信首页模块
		List<SiteConfigItemEntity>  moduleList = null;
		try {
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_WX_MODULE);
			moduleList = indexService.listIndexConfigItem(param);
			request.setAttribute("moduleList", moduleList);
		} catch (Exception e) {
			handleException("查询微信首页模块失败", logger, e);
		}
		
		// 查询微信首页广告
		List<SiteConfigItemEntity>  adList = null;
		try {
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_WX_AD);
			adList = indexService.listIndexConfigItem(param);
			request.setAttribute("adList", adList);
		} catch (Exception e) {
			handleException("查询微信首页广告失败", logger, e);
		}
		
		// 查询微信首页为你推荐商品
		List<SiteConfigItemEntity>  recommendList = null;
		// 过滤停用状态后的推荐商品
		List<SiteConfigItemEntity>  resultRecommendList = new ArrayList<SiteConfigItemEntity>();
		try {
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_WX_RECOMMEND);
			recommendList = indexService.listIndexConfigItem(param);
			
			if(recommendList != null && recommendList.size() > 0){
				for (SiteConfigItemEntity config : recommendList) {
					if(StringUtil.isNotEmpty(config.getProductCode())){
						String[] productInfo = config.getProductCode().split("##");
						config.setProductId(productInfo[0]);
						config.setProductName(productInfo[1]);
						config.setImagePath(productInfo[2]);
						
						// 过滤掉停用的商品展示
						if("1".equals(config.getConfigStatus())){
							resultRecommendList.add(config);
						}
					}
				}
			}
			request.setAttribute("recommendList", resultRecommendList);
		} catch (Exception e) {
			handleException("查询微信首页为你推荐商品", logger, e);
		}
		return "wx/home/index";
	}

	/**
	 * 查询首页主屏幕广告图片信息 （查询redis）
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author llp
 	 * @date 2017-09-26 14:44:49
	 */
	@RequestMapping("/listIndexRollingAD")
	@ResponseBody
	public List<SiteConfigItemEntity> listIndexRollingAD(HttpServletRequest request){
		List<SiteConfigItemEntity>  sciList = null;
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_AD);
			sciList = indexService.listIndexRollingAD(param);
		} catch (Exception e) {
			handleException("查询主屏幕广告图片信息失败", logger, e);
		}
		return sciList;
	}

	/**
	 * 查询首页商品类型 （查询redis）
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author llp
 	 * @date 2017-09-26 14:44:49
	 */
	@RequestMapping("/listIndexProductCategory")
	@ResponseBody
	public List<ProductCategoryEntity> listIndexProductCategory(HttpServletRequest request){
		List<ProductCategoryEntity>  pcList = null;
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_PRODUCT_CATEGORY);
			pcList = indexService.listIndexProductCategory(param);
		} catch (Exception e) {
			handleException("查询首页商品类型", logger, e);
		}
		return pcList;
	}
	
	
	/**
	 * 查询热门搜索词
	 * @param request
	 * @return
	 */
	@RequestMapping("/listHotSearchKey")
	@ResponseBody
	public List<KeyMapEntity> listHotSearchKey(HttpServletRequest request){
		List<KeyMapEntity>  kmList = null;
		try {
			kmList = keyMapService.listKeyMap("hotSearchKey");
		} catch (Exception e) {
			handleException("查询热门搜索词", logger, e);
		}
		return kmList;
	} 
	
	/**
	 * 查询首页底部指南信息
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author llp
 	 * @date 2017-09-26 14:44:49
	 */
	@RequestMapping("/footer")
	@ResponseBody
	public Map<String, List<SiteConfigItemEntity>> listIndexFingerPost(HttpServletRequest request){
		Map<String, List<SiteConfigItemEntity>> resultMap = new HashMap<String, List<SiteConfigItemEntity>>();
		// 网站指南
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, List<SiteConfigItemEntity>> sccMap = null;
		try {
			// 查询网站指南类信息
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_FINGER_POST);
			sccMap = indexService.listIndexFingerPost(param);
			resultMap.put("qaList",sccMap.get(IndexConstants.DB_KEY_SITE_CONFIG_FINGER_QA));
			resultMap.put("shoppingList", sccMap.get(IndexConstants.DB_KEY_SITE_CONFIG_FGINER_SHOPPING));
			resultMap.put("deliveryList", sccMap.get(IndexConstants.DB_KEY_SITE_CONFIG_FGINER_DELIVERY));
			resultMap.put("payTypeList", sccMap.get(IndexConstants.DB_KEY_SITE_CONFIG_FGINER_PAY_TYPE));
			resultMap.put("afterSalesList", sccMap.get(IndexConstants.DB_KEY_SITE_CONFIG_FGINER_AFTER_SALES));
			
		} catch (Exception e) {
			handleException("查询网站指南失败", logger, e);
		}
		return resultMap;
	}
	
	
	
	/**
	 * 查询客户的本周、本月订货情况
	 * @param request
	 * @return
	 */
	@RequestMapping("/listCustomerOrderStatistics")
	@ResponseBody
	public Map<String, String> listCustomerOrderStatistics(HttpServletRequest request){
		Map<String, String> resultMap = new HashMap<String, String>();
		if(!isLogin(request)){
			resultMap.put("TO_PAY_NUM", "0");
			resultMap.put("TO_SEND_NUM", "0");
			resultMap.put("TO_RECEIVE_NUM", "0");
			resultMap.put("OVERDUED_NUM", "0");
			resultMap.put("CUR_WEEK_NUM", "0");
			resultMap.put("CUR_MONTH_NUM", "0");
		}else{
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("customerId", getUserCode());
			param.put("curWeekStartTime", DateUtils.getCurWeek());
			param.put("curMonthStartTime", DateUtils.getCurMonth());
			List<CustomerOrderStatisticsEntity> cosList = orderService.listCustomerOrderStatistics(param);
			Map<String, String> tmpMap = new HashMap<String, String>();
			if(cosList != null && cosList.size() > 0){
				for (CustomerOrderStatisticsEntity order : cosList) {
					tmpMap.put(order.getOrderStatus(), order.getOrderNum());
				}
			}
			
			String toPayNum = tmpMap.get(OrderConstants.ORDER_STATUS.WAIT_TO_PAY.getCode());
			String toSendNum = tmpMap.get(OrderConstants.ORDER_STATUS.WAIT_TO_SEND.getCode());
			String toReciveNum = tmpMap.get(OrderConstants.ORDER_STATUS.WAIT_TO_RECEIVE.getCode());
			String overduedNum = tmpMap.get("OVERDUED_NUM");
			String curWeekNum = tmpMap.get("CUR_WEEK_NUM");
			String curMonthNum = tmpMap.get("CUR_MONTH_NUM");
			
			resultMap.put("TO_PAY_NUM", StringUtil.isNotEmpty(toPayNum)?toPayNum:"0");
			resultMap.put("TO_SEND_NUM", StringUtil.isNotEmpty(toSendNum)?toSendNum:"0");
			resultMap.put("TO_RECEIVE_NUM", StringUtil.isNotEmpty(toReciveNum)?toReciveNum:"0");
			resultMap.put("OVERDUED_NUM", StringUtil.isNotEmpty(overduedNum)?overduedNum:"0");
			resultMap.put("CUR_WEEK_NUM", StringUtil.isNotEmpty(curWeekNum)?curWeekNum:"0");
			resultMap.put("CUR_MONTH_NUM", StringUtil.isNotEmpty(curMonthNum)?curMonthNum:"0");
		}
		
		return resultMap;
	}
	
	/**
	 * 查询首页楼层商品的动态价格
	 * @param request
	 * @return
	 */
	@RequestMapping("/listFloorProductPrice")
	@ResponseBody
	public List<ProductEntity> listFloorPorductPrice(HttpServletRequest request){
		Map<String, Object> param = new HashMap<String, Object>();
		List<ProductEntity> priceList= null;
		String customerLevel = getCustomerLevel();
		String productIds = request.getParameter("productIds");
		if(StringUtil.isNotEmpty(productIds)){
			List<String> productIdsList = new ArrayList<String>();
			if(StringUtil.isNotEmpty(productIds)){
				for (String productId : productIds.split(",")) {
					productIdsList.add(productId);
				}
			}
			param.put("customerLevel", customerLevel);
			param.put("productIdsList", productIdsList);
			param.put("isLogin", isLogin(request)?"1":"0");
			priceList= productService.listFoorProductPrice(param);	
		}
		return priceList;
	}
	
	
	
}
